package org.fluidripple.socket.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.fluidripple.socket.inbound.ClientEventHandler;
import org.fluidripple.socket.operation.AutomationOperation;
import org.fluidripple.socket.operation.ChannelOperation;
import org.fluidripple.socket.session.Session;
import org.fluidripple.socket.session.SessionManager;
import org.fluidripple.socket.stickhalf.FixedLengthDecoderImpl;
import org.fluidripple.socket.wrapper.DataWrapper;
import org.springframework.stereotype.Component;

/**
 * 查询设备序列号
 */
@Slf4j
@Component
public class DeviceSerializableProtocol extends Protocol{


    @Override
    public void writer(Channel channel) {
        ChannelOperation.replaceChannelHandler(channel,ClientEventHandler.name, FixedLengthDecoderImpl.name,new FixedLengthDecoderImpl(9));
        log.info("发送查询设备序列号指令.....");
        Session session = SessionManager.getSession(channel);
        session.setProtocol(this);
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(ByteBufUtil.decodeHexDump("F0C103C0C3"));
        channel.writeAndFlush(buf);

    }

    @Override
    public void toDecode(DataWrapper dataWrapper) {
        ByteBuf buf = dataWrapper.getBuf();
        buf.skipBytes(4);
        String deviceSerializable = buf.readInt()+"";
        log.info("获取到设备序列号：{}",deviceSerializable);
        Session session = dataWrapper.getSession();
        session.setDeviceSerializable(deviceSerializable);
        SessionManager.register(session);
        Channel channel = session.getChannel();
        AutomationOperation.startCollect(channel);
    }


}
